<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\StudentsModel;
use App\Model\Class2Model;
use Illuminate\Support\Facades\DB;
use Cache;
use function Couchbase\defaultEncoder;

class AdminController extends Controller
{
    //    2021 5 11 新增 start
    public function getActivityTime(){
//        请求数据库
        $res=DB::table('timeconfig')->first();
//       失败
        if (!$res){
            return json_encode(['error_code'=>2,'msg'=>'获取失败','data'=>$res]);
        }
//      成功
        return json_encode(['error_code'=>0,'msg'=>'获取成功','data'=>$res]);
    }

    public function changeActivityTime(Request $requst){
//    接收前端参数start
      $data=['starttime'=>$requst->input('starttime')
          ,'endtime'=>$requst->input('endtime')];//临时对象 用来存储准备更新的数据
//    接收前端参数end
//    必要参数校验 start
      foreach ($data as $key=>$value){
          if (!$value){
             return json_encode(['error_code'=>1,'msg'=>'缺少参数'.$key,'data'=>$value]);
          }
      }
//    必要参数校验 end
      $res=DB::table('timeconfig')->updateOrInsert(['id'=>1],$data);
//    失败时
      if (!$res){
          return json_encode(['error_code'=>2,'msg'=>'修改失败','data'=>$res]);
      }
//    成功时
      return json_encode(['error_code'=>0,'msg'=>'修改成功','data'=>$res]);

    }

//    2021 5 11 新增 end




    //登录
    public function login_POST(Request $requst)
    {
        //用户名
        $username = $requst->request->get('username');
        //密码
        $pwd = $requst->request->get('password');

        //判断非空
        if (!($pwd && $username)) {
            die(\json_encode(['error'=>'用户名或者密码不能为空']));
        }

        //返回值
        $return = null;
        //获得admin配置
        $adminConfig = \config('my.admin');
        if ($username == $adminConfig['username'] && $pwd == $adminConfig['password']) {
            $return = [
                'token'=>PublicController::getJwt('admin', $username),
                'data'=>[
                    'stu_id'=>$username,
                    'name'=>'管理员',
                    ]
            ];
        } else {
            $return = [
                'error'=>'用户名或者密码错误'
            ];
        }

        return json_encode($return);
    }

    //导入学生
    public function students_POST(Request $requst)
    {
        //学生列表
        $students = $requst->input('students');
        $students=json_decode($students,true);
        $studentsTab=DB::table('students');
        $resAll=[];
        foreach ($students as $key=>$val){
            $stu_id=$val['stu_id'];
            unset($val['stu_id']);
            if(!isset($val['password'])){
                $val['password']='stu'.$stu_id;
            }
            if(!isset($val['wished_times'])){
                $val['wished_times']=0;
            }
            $res= DB::table('students')->updateOrInsert(['stu_id'=>$stu_id],$val);
            $resAll[$stu_id]=$res;
        }
        return json_encode(['error'=>false,'msg'=>'成功','data'=>$resAll]);
        //
////获取全部字段
//        $stu_id ='全部字段';
//        $studentsTab->insert(['stu_id'=>$stu_id]);
//        $allFields=$studentsTab->where(['stu_id'=>$stu_id])->first();
//        $studentsTab->where(['stu_id'=>$stu_id])->delete();
//        $allFields=json_decode(json_encode($allFields),true);
////获取全部字段
//
//









//        $res= DB::table('students')->insert([
//            ['stu_id'=>'1000','name'=>null],
//            ['stu_id'=>'1001','name'=>'张三'],
//        ]);
//
//        return json_encode($res);
//
//
//
//        if ($students){
//            if (!count($students)){
//                return json_encode(['error'=>'没有数据']);
//            }
//
//        }else{
//            return json_encode(['error'=>'没有数据']);
//        }
//
//        return  json_encode($students);






//        暂停  2021 5 28 21 ：26  预计 择日 8点20 继续


//        DB::table('students')->insertOrIgnore([
//            ['id' => 1, 'email' => 'taylor@example.com'],
//            ['id' => 2, 'email' => 'dayle@example.com']
//        ]);






//
//        return json_encode($students);
//        //读取配置中的允许作答次数
//        $times = 0;
//
//        //遍历过滤
//        foreach ($students as $k=>$y) {
//            if (StudentsModel::find($y['stu_id'])) {
//                return json_encode(['error'=>'学号重复['.$y['stu_id'].']']);
//            }
//            $students[$k]['wished_times'] = $times;
//            $students[$k]['password'] = 'stu'.$y['stu_id'];
//            //#在此处添加字段验证，单招.......
//        }
//
//        //返回值
//        $returnVal = null;
//        try {
//            StudentsModel::insert($students);
//            $returnVal = json_encode(['message'=>'添加成功']);
//        } catch (\Illuminate\Database\QueryException $e) {      //捕捉异常
//            $returnVal = json_encode(['error'=>'添加失败']);
//        }
//        return $returnVal;
    }

    // 成绩导入修改
    public function scores_POST(Request $requst)
    {
        //成绩信息
        $scores = $requst->request->get('scores');

        //返回值
        $returnVal = null;

        //开启回滚
        DB::beginTransaction();
        try {
            //遍历过滤
            foreach ($scores as $k=>$y) {
                //#在此处判断接受到的字段是否合法
                $res_db = StudentsModel::where([['stu_id',$y['stu_id']],['name',$y['name']]])->first();
                if (!$res_db) {
                    die(json_encode(['error'=>'姓名和学号不匹配']));
                } else {
                    $res_db->update(['score_python' => $y['score_python'],'score_php' => $y['score_php']]);
                    $res_db->save();
                }
            }
            $returnVal = json_encode(['message'=>'修改成功']);
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = json_encode(['error'=>'修改失败']);
            //回滚
            DB::rollBack();
        }
        return $returnVal;
    }

    //查看学生
    public function students_GET(Request $requst)
    {
        //每页条数
        $limit = ($requst->limit=='')?config('my.getinfo')['limit']:$requst->limit;

        //第几页
        $start = ($requst->start=='')?1:$requst->start;

        //是否查找全部 1为是，其他为否
        $all = $requst->all;

        //班级列表
        $class = $requst->class;


        //在此处验证，参数是否为数字，是否符合要求

        //返回值
        $returnVal = null;
        //判断是否有班级，有的话，按照班级查找
        if ($class) {
            //遍历班级
            foreach ($class as $k=>$y) {
                //在此处添加验证，班级是否存在
                $query = StudentsModel::where('class_base', $y);
                //判断是否查找全部
                if (!$all == 1) {
                    $query->offset(($start - 1) * $limit)
                    ->limit($limit);
                } else {
                    $limit = 'max';
                }
                $data_i = $query->get();//在此处添加要返回的字段
                $returnVal[] = ['class_base'=>$y,'count'=>count($data_i),'limit'=>$limit,'start'=>$start,'data'=>$data_i];
            }
        } else {
            //直接寻找

            //判断是否查找全部
            if (!$all == 1) {
                $data = StudentsModel::offset(($start - 1) * $limit)
                ->limit($limit)
                ->get();//在此处添加要返回的字段
            } else {
                $data = StudentsModel::get();//在此处添加要返回的字段
                $limit = 'max';
            }
            $returnVal[] = ['count'=>count($data),'limit'=>$limit,'start'=>$start,'data'=>$data];
        }


        die(\json_encode($returnVal));
    }

    //搜索
    public function search_GET(Request $requst)
    {
        //姓名
        $name = $requst->name;
        //学号
        $stu_id = $requst->stu_id;

        //判断字段是否为空

        //优先按照学号搜索
        //返回值
        $returnVal = null;
        if ($stu_id) {
            $returnVal = StudentsModel::where('stu_id', $stu_id)->get();
        } elseif ($name) {
            $returnVal = StudentsModel::where('name', $name)->get();
        } else {
            $returnVal = ['error'=>'404'];
        }

        return json_encode(['data'=>$returnVal]);
    }

    //志愿成绩修改,班级
    public function score_wish_PUT(Request $requst)
    {
        //成绩信息
        $score_wish = $requst->request->get('score_wish');

        //#在此处判断接受到的字段是否合法

        //返回值
        $returnVal = null;

        //开启回滚
        DB::beginTransaction();
        try {
            //遍历过滤
            foreach ($score_wish as $k=>$y) {
                //#在此处判断接受到的字段是否合法
                $res_db = StudentsModel::where([['stu_id',$y['stu_id']],['name',$y['name']]])->first();
                if (!$res_db) {
                    die(json_encode(['error'=>'姓名和学号不匹配']));
                } else {
                    //wish对象
                    $wish = $y['wish'];
                    //在这里进行专业验证，先加一个简单的去重
                    if ($wish!=array_unique($wish)) {
                        die(json_encode(['error'=>'专业重复']));
                    }

                    // 在这里进行验证，看看那些需要修改


                    $updateData=[
                        'score_python' => $y['score_python'],
                        'score_php' => $y['score_php'],
                        'class_new_id'=>$y['class_new_id'],
                    ];
                    foreach ($wish as $key=>$value){
                        $updateData[$key]=$value;
                    }

                    $res_db->update($updateData);
                    $res_db->save();
                }
            }
            $returnVal = json_encode(['message'=>'修改成功']);
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = json_encode(['error'=>'修改失败']);
            //回滚
            DB::rollBack();
        }
        return $returnVal;
    }

    //成绩规则修改
    public function scorerule_POST(Request $requst)
    {
        //规则
        $rule = $requst->request->get('rule');

        //判断是否传入规则
        if ($rule) {
            //添加验证，判断json是否符合规范
            Cache::forever('score_rule', $rule);
        } else {
            //未传入规则的话，读取缓存，缓存没有则读取配置文件
            $rule = Cache::get('score_rule', \config('my.score_rule'));
        }


        //php成绩没有的
        $php_db = StudentsModel::where('score_php', null)->get();

        //python成绩没有的
        $php_python = StudentsModel::where('score_python', null)->get();

        //空保存
        $null = [];
        foreach ($php_db as $k=>$y) {
            $null['php'][] = ['name'=>$y->name,'stu_id'=>$y->stu_id];
        }
        foreach ($php_python as $k=>$y) {
            $null['python'][] = ['name'=>$y->name,'stu_id'=>$y->stu_id];
        }

        if (count($null)) {
            die(json_encode(['error'=>'部分学生成绩为空','data'=>$null]));
        }

        //返回值
        $returnVal = null;
        //判断是否有成绩为空的学生
        //开启回滚
        DB::beginTransaction();
        try {
            //开始更改学生综合成绩
            foreach (StudentsModel::get() as $k=>$y) {
                $y->score_end = $y['score_python'] * $rule['score_python']  + $y['score_php'] * $rule['score_php'];
                $y->save();
            }
            $returnVal = ['message'=>'综合成绩修改成功'];
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = ['error'=>'综合成绩修改失败'];
            //回滚
            DB::rollBack();
        }

        return json_encode($returnVal);
    }

    //获得大二班级
    public function class2_GET(Request $requst)
    {
        return json_encode(Class2Model::get());
    }

    //大二班级管理
    public function class2_POST(Request $requst)
    {
        //操作
        $operating = $requst->request->get('operating');

        //返回值
        $returnVal = null;
        //开启回滚
        DB::beginTransaction();
        try {
            //班级
            $class = $requst->request->get('class');
            //班级id
            $id = $requst->request->get('id');
            if ($operating == 1) {
                //创建班级
                Class2Model::insert(['name'=>$class['name'],'subject'=>$class['subject'],'maxcapacity'=>$class['maxcapacity']]);
                $returnVal = ['message'=>'班级添加成功'];
            } elseif ($operating == 0) {
                //修改
                $res_db = Class2Model::where('id', $id)->first();

                $res_db->update(['name'=>$class['name'],'subject'=>$class['subject'],'maxcapacity'=>$class['maxcapacity']]);
                $returnVal = ['message'=>'班级修改成功'];
            } elseif ($operating == -1) {
                //删除
                $res_db = Class2Model::where('id', $id)->first();
                if ($res_db) {
                    $res_db->delete();
                    $returnVal = ['message'=>'班级删除成功'];
                } else {
                    $returnVal = ['error'=>'班级不存在'];
                }
            }
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = ['error'=>'班级操作失败'];
            //回滚
            DB::rollBack();
        }

        return json_encode($returnVal);
    }

    //自动分配班级
    public function classchanges_GET(Request $requst)
    {
        $returnVal = null;
        DB::beginTransaction();
        try {
            //判断是否有综合成绩为空的人
            $res_end_null = StudentsModel::where('score_end', null)->get();

            if ($res_end_null->count()) {
                //根据缓存，进行综合成绩计算
                self::scorerule_POST($requst);
            }

            //判断是否有没有选课的人
            $res_db = StudentsModel::where('wish1', null)->get();
            if ($res_db->count()) {
                $list = [];
                foreach ($res_db as $k=>$y) {
                    $list[] = ['name'=>$y->name,'stu_id'=>$y->stu_id];
                }

                die(json_encode(['error'=>'部分同学没有填报志愿','data'=>$list]));
            }

            //当前专业列表
            $subjectlist = array_keys(config('my.class2'));
            $subjectlist=DB::table('direction')->select('dir_name')->get();
            $arr=[];
            foreach ($subjectlist as $item){
                array_push($arr,$item->dir_name);
            }
            $subjectlist=$arr;

            //存储每个专业所要的最大容量,专业拥有的班级，班级个数
            $subject_info = [];

            //所有班级总容量
            $allclasscapacity = 0;

            //存储已经每个方向分入了多少人
            $completedCount = [];

            foreach ($subjectlist as $k=>$y) {
                $completedCount[$y] = 0;
                //查找专业班级数
                $res_class = Class2Model::where('subject', $y);

                //判断每个专业是否有对应的班级
                if (!$res_class->count()) {
                    die(json_encode(['error'=>'['.$y.']专业还没有分配班级']));
                }

                //每个班级的人数看做是相同的

                //班级个数
                $count = $res_class->count();

                //班级总容量和班级名称
                $capacity = $res_class->get()->reduce(function ($res, $item) {
                    $res['maxcapacity'] = isset($item['maxcapacity'])?$res['maxcapacity']+$item['maxcapacity']:0;

                    $res['list'][] = $item['name'];
                    return $res;
                });

                //添加到总容量
                $allclasscapacity += $capacity['maxcapacity'];
                $subject_info[$y] = ['capacity'=>$capacity['maxcapacity'],'idlist'=>$capacity['list'],'count'=>$count];
            }

            //判断当前总学生数是否大于班级总容量
            if (StudentsModel::count()>$allclasscapacity) {
                die(\json_encode(['error'=>'班级容量小于学生总量,班级容量：['.$allclasscapacity.'],学生数量：['.StudentsModel::count().']']));
            }

            //分配学生开始

            //存储已经分配了的学生的学号
            $completed = [];

            //遍历志愿
//            ['wish1','wish2','wish3','wish4','wish5','wish6']
//            return json_encode($subjectlist);
            foreach ($subjectlist as $index=>$wish) {
                //遍历专业
                $wish= 'wish'.strval($index+1);
                foreach ($subject_info as $subject=>$info) {
                    if($subject_info[$subject]["capacity"] == 0){
                        continue;
                    }
                    //获得志愿*中选择专业为*的学生
                    $res_db_stu = StudentsModel::whereNotIn('stu_id', $completed)->where($wish, $subject);

                    //判断是否有学生
                    if ($res_db_stu->count() == 0) {
                        continue;
                    }

                    //判断当前志愿选择专业的人数与当前专业剩余容量，选择是否截取
                    if ($res_db_stu->count()>=$subject_info[$subject]['count']) {
                        $students = $res_db_stu->orderBy('score_end', 'desc')->limit($subject_info[$subject]['capacity'])->get();
                        foreach ($students as $index_student=>$student) {
                            $completed[] = $student->stu_id;

                            //按照顺序划分班级
                            $class2_id = $info['idlist'][($completedCount[$subject]+$index_student) % $info['count']];
                            $student->class_new_id = $class2_id;
                            $student->class_first_id = $class2_id;
                            $student->save();
                            $subject_info[$subject]['capacity']-=1;
                        }
                        //将本次分班学生数量记录下来
                        $completedCount[$subject]+=$students->count();
                    } else {
                        $students = $res_db_stu->orderBy('score_end', 'desc')->get();
                        foreach ($students as $index_student=>$student) {
                            $completed[] = $student->stu_id;

                            //按照顺序划分班级
                            $class2_id = $info['idlist'][$index_student % $info['count']];
                            $student->class_new_id = $class2_id;
                            $student->class_first_id = $class2_id;
                            $student->save();
                            $subject_info[$subject]['capacity']-=1;
                        }
                    }
                }
            }
            $returnVal = ['message'=>'班级分配成功'];
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = ['error'=>'班级分配操作失败,数据库修改失败'];
            //回滚
            DB::rollBack();
        }
        return json_encode($returnVal);
    }
}
